package com.java110.mall.cart.bmo.inoutOrder.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.java110.mall.cart.bmo.inoutOrder.ISaveInoutOrderBMO;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.inoutOrder.InoutOrderDto;
import com.java110.dto.product.ProductSpecValueDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.cart.IInoutOrderInnerServiceSMO;
import com.java110.intf.cart.IInoutOrderProductInnerServiceSMO;
import com.java110.intf.goods.IProductSpecValueInnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.po.inoutOrder.InoutOrderPo;
import com.java110.po.inoutOrder.InoutOrderProductPo;
import com.java110.utils.constant.StateConstant;
import com.java110.utils.exception.CmdException;
import com.java110.utils.util.Assert;
import com.java110.utils.util.ListUtil;
import com.java110.utils.util.StringUtil;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service("saveInoutOrderBMOImpl")
public class SaveInoutOrderBMOImpl implements ISaveInoutOrderBMO {

    @Autowired
    private IInoutOrderInnerServiceSMO inoutOrderInnerServiceSMOImpl;

    @Autowired
    private IInoutOrderProductInnerServiceSMO iInoutOrderProductInnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userInnerServiceSMOImpl;

    @Autowired
    private IProductSpecValueInnerServiceSMO productSpecValueInnerServiceSMOImpl;


    /**
     * 添加小区信息
     *
     * @param reqJson
     * @return 订单服务能够接受的报文
     */
    @Java110Transactional
    public ResponseEntity<String> save(JSONObject reqJson) {

        if (!reqJson.containsKey("inoutOrderProducts")) {
            throw new IllegalArgumentException("请求报文格式错误");
        }

        JSONArray inoutOrderProducts = reqJson.getJSONArray("inoutOrderProducts");
        if (inoutOrderProducts == null || inoutOrderProducts.size() < 1) {
            throw new IllegalArgumentException("未包含商用");
        }

        InoutOrderPo inoutOrderPo = new InoutOrderPo();
        inoutOrderPo.setOrderId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_orderId));
        inoutOrderPo.setShopId(reqJson.getString("shopId"));
        inoutOrderPo.setState(InoutOrderDto.STATE_W);
        inoutOrderPo.setOrderType(reqJson.getString("orderType"));
        inoutOrderPo.setPersonId(reqJson.getString("personId"));
        UserDto userDto = new UserDto();
        userDto.setUserId(reqJson.getString("personId"));
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);

        Assert.listOnlyOne(userDtos, "未包含用户信息");
        inoutOrderPo.setPersonName(userDtos.get(0).getName());
        if(!StringUtil.isNullOrNone(reqJson.getString("relOrderId"))){
            inoutOrderPo.setRelOrderId(reqJson.getString("relOrderId"));
        }
        inoutOrderPo.setRemark(reqJson.getString("remark"));
        //开始保存 inoutOrderProduct
        InoutOrderProductPo inoutOrderProductPo = null;
        List<InoutOrderProductPo> inoutOrderProductPos = new ArrayList<>();
        for (int inoutOrderProductIndex = 0; inoutOrderProductIndex < inoutOrderProducts.size(); inoutOrderProductIndex++) {
            inoutOrderProductPo = new InoutOrderProductPo();
            inoutOrderProductPo.setRsId(reqJson.getString("rsId"));
            inoutOrderProductPo.setSupplierName(reqJson.getString("supplierName"));
            inoutOrderProductPo.setPrice(inoutOrderProducts.getJSONObject(inoutOrderProductIndex).getString("price"));
            inoutOrderProductPo.setProdCount(inoutOrderProducts.getJSONObject(inoutOrderProductIndex).getString("count"));
            BigDecimal price = new BigDecimal(Double.parseDouble(inoutOrderProductPo.getPrice()));
            price = price.multiply(new BigDecimal(Double.parseDouble(inoutOrderProductPo.getProdCount()))).setScale(2, BigDecimal.ROUND_HALF_EVEN);
            inoutOrderProductPo.setAmount(price.doubleValue() + "");
            inoutOrderProductPo.setItemId(GenerateCodeFactory.getGeneratorId("11"));
            inoutOrderProductPo.setOrderId(inoutOrderPo.getOrderId());
            inoutOrderProductPo.setProductId(inoutOrderProducts.getJSONObject(inoutOrderProductIndex).getString("productId"));
            inoutOrderProductPo.setProdName(inoutOrderProducts.getJSONObject(inoutOrderProductIndex).getString("prodName"));
            inoutOrderProductPo.setShopId(inoutOrderPo.getShopId());
            inoutOrderProductPo.setState(InoutOrderDto.STATE_W);
            inoutOrderProductPo.setValueId(inoutOrderProducts.getJSONObject(inoutOrderProductIndex).getString("valueId"));
            inoutOrderProductPo.setRemark(inoutOrderProducts.getJSONObject(inoutOrderProductIndex).getString("remark"));
            inoutOrderProductPo.setSpecName(inoutOrderProducts.getJSONObject(inoutOrderProductIndex).getString("specName"));
            inoutOrderProductPos.add(inoutOrderProductPo);
            //如果是出库 判断库存是否足够
            if (InoutOrderDto.ORDER_TYPE_IN.equals(inoutOrderPo.getOrderType())) {
                continue;
            }

            ProductSpecValueDto productSpecValueDto = new ProductSpecValueDto();
            productSpecValueDto.setShopId(inoutOrderProductPo.getShopId());
            productSpecValueDto.setValueId(inoutOrderProductPo.getValueId());
            productSpecValueDto.setProductId(inoutOrderProductPo.getProductId());
            List<ProductSpecValueDto> productSpecValueDtos = productSpecValueInnerServiceSMOImpl.queryProductSpecValues(productSpecValueDto);

            Assert.listOnlyOne(productSpecValueDtos, "商品不存在");

            long stock = Long.parseLong(productSpecValueDtos.get(0).getStock());

            if (stock < Long.parseLong(inoutOrderProductPo.getProdCount())) {
                throw new IllegalArgumentException(inoutOrderProductPo.getProdName() + "库存不足");
            }
        }


        int flag = iInoutOrderProductInnerServiceSMOImpl.saveInoutOrderProducts(inoutOrderProductPos);

        if (flag < 1) {
            throw new IllegalArgumentException("提交失败");
        }

        flag = inoutOrderInnerServiceSMOImpl.saveInoutOrder(inoutOrderPo);

        if (flag < 1) {
            throw new IllegalArgumentException("提交失败");
        }
        return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
    }

    @Override
    public ResponseEntity<String> audit(JSONObject reqJson) {
        InoutOrderPo inoutOrderPo = new InoutOrderPo();
        String state = reqJson.getString("state");
        inoutOrderPo.setOrderId(reqJson.getString("orderId"));
        inoutOrderPo.setShopId(reqJson.getString("shopId"));

        // 查询订单
        InoutOrderDto inoutOrderDto = new InoutOrderDto();
        inoutOrderDto.setOrderId(inoutOrderPo.getOrderId());
        inoutOrderDto.setShopId(inoutOrderPo.getShopId());
        List<InoutOrderDto> inoutOrderDtos = inoutOrderInnerServiceSMOImpl.queryInoutOrders(inoutOrderDto);
        if(ListUtil.isNull(inoutOrderDtos)){
            throw new CmdException("订单不存在");
        }

        if (StateConstant.AGREE_AUDIT.equals(state)) {
            if(InoutOrderDto.ORDER_TYPE_IN.equals(inoutOrderDtos.get(0).getOrderType())) {
                inoutOrderPo.setState(InoutOrderDto.STATE_WI);
            }else{
                inoutOrderPo.setState(InoutOrderDto.STATE_WO);
            }
        } else {
            inoutOrderPo.setState(InoutOrderDto.STATE_AF);
        }
        int flag = inoutOrderInnerServiceSMOImpl.updateInoutOrder(inoutOrderPo);
        if (flag < 1) {
            throw new IllegalArgumentException("审核失败");
        }

        InoutOrderProductPo inoutOrderProductPo = new InoutOrderProductPo();
        inoutOrderProductPo.setOrderId(inoutOrderPo.getOrderId());
        inoutOrderProductPo.setState(inoutOrderPo.getState());
        inoutOrderProductPo.setShopId(inoutOrderPo.getShopId());
        flag = iInoutOrderProductInnerServiceSMOImpl.updateInoutOrderProduct(inoutOrderProductPo);

        if (flag < 1) {
            throw new IllegalArgumentException("审核失败");
        }

        return ResultVo.success();
    }

}
